// Copyright (C) 2010 Razvan Constantin <razvan.constantin@rconst.net>
//
// This file is part of FileBow.
//
// FileBow is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// FileBow is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with FileBow.  If not, see <http://www.gnu.org/licenses/>.

#include "common.h"

#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
#include <sstream>

using namespace std;

vector<LogHandler> gLogHandlers;

void RegisterLogHandler(LogHandler handler) {
  gLogHandlers.push_back(handler);
}

class LogLevelNames {
  public: LogLevelNames() {
    names[LogLevel::LDBG] = "DEBUG";
    names[LogLevel::LINFO] = "INFO";
    names[LogLevel::LWARN] = "WARNING";
    names[LogLevel::LERR] = "ERROR";
  }
  public: const std::string& operator[](LogLevel::Value level) {
    return names[level];
  }
  private: map<LogLevel::Value, string> names;
} kLogLevelNames;

void StdErrLogHandler(LogLevel::Value level, const std::string& text) {
  cerr << kLogLevelNames[level] << ":" << text << endl;
}

void RegisterStdErrLogHandler() {
  RegisterLogHandler(StdErrLogHandler);
}

LogStream::LogStream(LogLevel::Value level, const string& file, int lineNumber) {
  this->level = level;
  line << file << ":" << lineNumber << ": ";
}

LogStream::~LogStream() {
  for (int i = 0; i < gLogHandlers.size(); ++i) {
    (*gLogHandlers[i])(level, line.str());
  }
  if (!fatal.empty()) {
    throw runtime_error(fatal);
  }
}
